//
//  CellViewController.m
//  WisdomZhuHai
//
//  Created by Ryan on 15-1-16.
//  Copyright (c) 2015年 wyd. All rights reserved.
//

#import "NewsCellViewController.h"
#import "DVSwitch.h"

@interface NewsCellViewController ()

@property (nonatomic,strong) UIView* headerView;
@property (nonatomic,strong) UIView* headerPopupView;

@property (nonatomic,assign) int currentIndex;
@property (nonatomic,strong) NSMutableArray* newsList;

@property (nonatomic, strong) NSMutableArray *array_categoryName;
@property (nonatomic, strong) NSMutableArray *array_categoryId;

@property (nonatomic, assign) int category_current;

@property (nonatomic, strong) DVSwitch *topSelectMenu;

@property (nonatomic, assign) int isMenuInited;

@property (nonatomic,strong)WebIOS *web;

@end

@implementation NewsCellViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.currentIndex = -1;
    self.category_current = 0;
    self.isMenuInited = 0;
    self.tableView.backgroundColor = [UIColor whiteColor];
    //    [self setEnableRefresh:YES];
    [self setEnableLoadMore:YES];//可以加载多项
    self.pullTableViewDelegate = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.frame = CGRectMake(0, self.headerView.bounds.size.height, self.view.bounds.size.width, self.view.bounds.size.height - self.headerView.bounds.size.height);
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0, self.tableView.bounds.size.width, 35)];
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.tableView.bounds.size.width, 0.f)];
    [self getList:self.category_current];
    
    self.array_categoryName = [[NSMutableArray alloc]init];
    self.array_categoryId = [[NSMutableArray alloc] init];
    
}

- (void)valueChanged:(id)sender{
    DVSwitch* segmentedControl = sender;
    NSLog(@"%s line:%d segment has changed to %d", __FUNCTION__, __LINE__, segmentedControl.
        selectedIndex);
    
    if(self.category_current != segmentedControl.selectedIndex){
        self.category_current = segmentedControl.selectedIndex;
        [self pullTableViewDidTriggerRefresh:self.tableView];
    }
}

- (void)initMenuWithArray{
    if(self.topSelectMenu == nil){
        self.topSelectMenu = [DVSwitch switchWithStringsArray:self.array_categoryName];
        self.topSelectMenu.frame = CGRectMake(0, 0, 320, 35);
        self.topSelectMenu.backgroundColor = [UIColor colorWithRed:235/255.0 green:235/255.0 blue:235/255.0 alpha:1];
        self.topSelectMenu.sliderColor = [UIColor colorWithRed:235/255.0 green:235/255.0 blue:235/255.0 alpha:1];
        self.topSelectMenu.labelTextColorInsideSlider = [UIColor colorWithRed:20/255.0 green:180/255.0 blue:220/255.0 alpha:1];
        self.topSelectMenu.labelTextColorOutsideSlider = [UIColor blackColor];
        self.topSelectMenu.cornerRadius = 5;
        [self.topSelectMenu addTarget:self action:@selector(valueChanged:) forControlEvents:UIControlEventValueChanged];
        [self.view addSubview:self.topSelectMenu];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Protocol request
- (void)getList:(int)category_id
{
    if(category_id == 0){
        [[ProtocolManager shareInstance] getNewsListWithCategoryId:0 andCount:20 beginNo:_currentIndex + 1 target:self selector:@selector(getListCallback:)];
    }else{
        [[ProtocolManager shareInstance] getNewsListWithCategoryId:[[self.array_categoryId objectAtIndex:category_id] intValue] andCount:20 beginNo:_currentIndex + 1 target:self selector:@selector(getListCallback:)];
    }
    
}

#pragma mark - Protocol call back

- (void)getListCallback:(NSDictionary*)dic
{
    NSLog(@"getListCallback %@", dic);
    if (dic == nil) {
        [self resetPullTableViewState];
        return;
    }
    if (self.currentIndex == -1) {
        self.newsList = [NSMutableArray array];
    }
    if([Common valueForKey:@"category" dic:dic] != nil || [[Common valueForKey:@"category" dic:dic] count] > 0){
        NSArray *array_temp = [NSArray arrayWithArray:[Common valueForKey:@"category" dic:dic]];
        
        if(self.isMenuInited == 0){
            for(NSDictionary *dic_temp in array_temp){
                [self.array_categoryId addObject:[Common valueForKey:@"id" dic:dic_temp]];
                [self.array_categoryName addObject:[Common valueForKey:@"name" dic:dic_temp]];
            }
            self.isMenuInited = 1;
        }
    }
    NSLog(@"%s || array_categoryId:%@, array_categoryName:%@", __FUNCTION__, self.array_categoryId, self.array_categoryName);
    NSArray* newsList = [Common valueForKey:P_LIST dic:dic];
    if ([newsList isKindOfClass:[NSArray class]]) {
        [self.newsList addObjectsFromArray:newsList];
        self.currentIndex += self.newsList.count;
    }
    if (newsList.count < STORE_LIST_RETURN_COUNT) {
        [self setEnableLoadMore:NO];
    }
    else {
        [self setEnableLoadMore:YES];
    }
    [self initMenuWithArray];
    
    [self resetPullTableViewState];
    [self.tableView reloadData];
}


#pragma mark - cell
- (void)cellSetup:(UITableViewCell*)cell index:(NSInteger)index;
{
    if (self.newsList.count <= 0) {
        return;
    }
    NSDictionary *cellDic = _newsList[index];
    NSString *imgUrl = [Common valueForKey:P_NPHOTO dic:cellDic];
    NSString *title = [Common valueForKey:P_NRTITLE dic:cellDic];
    NSArray *tagsList = [Common valueForKey:P_TAGS dic:cellDic];
    NSString *source_name = [Common valueForKey:P_V2_SOURCE_NAME dic:cellDic];
    NSString *comment_cnt = [Common valueForKey:P_V2_COMMENT_CNT dic:cellDic];
    UIImageView *image = (UIImageView*)[cell viewWithTag:1001];
    [image setImageWithURL:[Common getFullDownloadPathByRelativePath:imgUrl]];
    UILabel *titleLab = (UILabel*)[cell viewWithTag:1002];
    UIImageView *okImage = (UIImageView*)[cell viewWithTag:1007];
    okImage.hidden = YES;
    [titleLab setNumberOfLines:2];
    titleLab.text = title;
    [titleLab sizeToFit];
    CGRect frame = titleLab.frame;
    frame.size.width = 216;
    titleLab.frame = frame;
    [self tagSetup:tagsList titleLabHeight:frame.size.height cell:cell];
    UILabel *price = (UILabel*)[cell viewWithTag:1005];
    [price removeFromSuperview];
    UIImageView *districtNameImg = (UIImageView*)[cell viewWithTag:2001];
    [districtNameImg removeFromSuperview];
    UILabel *districtNameLab = (UILabel*)[cell viewWithTag:2002];
    districtNameLab.text = source_name;
    UIImageView* goodImg = (UIImageView*)[cell viewWithTag:2003];
    [goodImg removeFromSuperview];
    UILabel* CommontLab = (UILabel*)[cell viewWithTag:2006];
    CommontLab.text = comment_cnt;
}

//标签描绘
- (void)tagSetup:(NSArray*)tagsList titleLabHeight:(CGFloat)height cell:(UITableViewCell*)cell
{
    if(tagsList.count <= 0)
    {
        return;
    }
    CGFloat tagX = 0.0;
    int count = [tagsList count] > 3 ? 3 : [tagsList count];
    for (int i = 0; i < count; i++) {
        UIView* tagListView = nil;
        if (height < 20.0) {
            tagListView = [cell viewWithTag:1003];
        } else {
            tagListView = [cell viewWithTag:1004];
        }
        NSDictionary *tagDic = tagsList[i];
        NSArray *rgbArray = [[Common valueForKey:P_V2_RGB dic:tagDic] componentsSeparatedByString:@"#"];
        NSString *rgb = [NSString stringWithFormat:@"%@%@", @"0x",@"18aaf6"];
        if (rgbArray.count > 1) {
            rgb = [NSString stringWithFormat:@"%@%@", @"0x",rgbArray[1]];
        }
        NSString *name = [Common valueForKey:P_NAME dic:tagDic];
        UIView *tagView = [[UIView alloc] initWithFrame:CGRectMake(tagX, 0, 45, 16)];
        tagView.layer.cornerRadius = 3.0;
        unsigned int color = strtoul([rgb UTF8String],0,0);//nsstring 转 rgb
        tagView.backgroundColor = [Common colorWithRGB:color];
        UILabel *tagNameLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, tagView.frame.size.width, tagView.frame.size.height)];
        tagNameLab.font = [UIFont fontWithName:@"TrebuchetMS-Bold" size:10.0];
        tagNameLab.textAlignment = UITextAlignmentCenter;
        tagNameLab.textColor = [UIColor whiteColor];
        tagNameLab.text = name;
        [tagNameLab sizeToFit];
        CGRect frame = tagNameLab.frame;
        frame.size.width = MAX(tagNameLab.frame.size.width + 5, 45);
        frame.size.height = 16;
        frame.origin = tagView.frame.origin;
        tagView.frame = frame;
        frame.origin = tagNameLab.frame.origin;
        tagNameLab.frame = frame;
        [tagView addSubview:tagNameLab];
        [tagListView addSubview:tagView];
        tagX += tagView.frame.size.width + 5;
    }
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.newsList.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 85;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CommonCell"];
    // Configure the cell...
    if(cell == nil)
    {
        cell = [[NSBundle mainBundle] loadNibNamed:@"CommonCell"  owner:self options:nil][0];
    }
    [self cellSetup:cell index:indexPath.row];
    return cell;
}

#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row >= self.newsList.count) {
        return;
    }
    NSDictionary* dic = self.newsList[indexPath.row];
    NSString *url = [Common valueForKey:P_URL dic:dic];
    self.web = [[WebIOS alloc]initWithFrame:[Common shareInstance].contentFrame url:[Common getUrlByString:url]];
    self.web.target_id = [[Common valueForKey:@"id" dic:dic] intValue];
    self.web.type = @"NEWS";
    self.web.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:self.web animated:YES];
}

#pragma mark - PullTableViewDelegate
- (void)pullTableViewDidTriggerRefresh:(PullTableView*)pullTableView
{
    NSLog(@"refresh...");
    [self.tableView setContentOffset:CGPointMake(0, 0) animated:YES];
    [self setPullTableIsLoadMore:YES];
    self.currentIndex = -1;
    [self getList:self.category_current];
}

-(void)pullTableViewDidTriggerLoadMore:(PullTableView *)pullTableView
{
    NSLog(@"loadMore...");
    [self getList:self.category_current];
}

- (void)resetPullTableViewState
{
    [self setPullTableIsRefreshing:NO];
    [self setPullTableIsLoadMore:NO];
}


@end
